package com.shawn.dubbo.api;

import com.shawn.commons.utils.CommentType;
import com.shawn.model.mongo.Comment;
import com.shawn.model.mongo.Movement;
import com.shawn.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.Objects;

@DubboService
public class CommentsApiImpl implements CommentsApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查找评论表有无当前id的点赞记录
     *
     * @param userId 用户id
     * @param id     id
     * @return {@link Integer}
     */
    @Override
    public Boolean whetherLikeOrLove(Long userId, String id, CommentType commentType) {
        Query query = new Query();
        query.addCriteria(Criteria.where("publishId").is(new ObjectId(id)))
                .addCriteria(Criteria.where("userId").is(userId))
                .addCriteria(Criteria.where("commentType").is(commentType.getType()));
        return mongoTemplate.exists(query, Comment.class);
    }

    /**
     * 得到所有评论
     *
     * @param id       id
     * @param page     页面
     * @param pageSize 页面大小
     * @return {@link PageResult}<{@link Comment}>
     */
    @Override
    public PageResult<Comment> getAllComments(String id, Integer page, Integer pageSize,CommentType commentType) {
        Query query = new Query(Criteria.where("publishId").is(new ObjectId(id)))
                .addCriteria(Criteria.where("commentType").is(commentType.getType()));
        long count = mongoTemplate.count(query, Comment.class);
        query.skip((long) (page - 1) *pageSize)
                .limit(pageSize)
                .with(Sort.by(Sort.Order.desc("likeCount")))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);

        return new PageResult<>(page,pageSize, (int) count,comments);
    }

    /**
     * 保存评论 点赞 喜欢
     *
     * @param commentEntity 评论实体
     */
    @Override
    public Integer saveComments(Comment commentEntity) {
        mongoTemplate.save(commentEntity);
        //创建查询字段
        Query query = new Query(Criteria.where("id").is(commentEntity.getPublishId()));
        Update update = new Update();
        //更新动态的点赞,评论,或者喜欢数
        if (Objects.equals(commentEntity.getCommentType(), CommentType.LIKE.getType())){
            //点赞
            update.inc("likeCount",1);
        }
        if (Objects.equals(commentEntity.getCommentType(),CommentType.LOVE.getType())){
            update.inc("loveCount",1);
        }
        if (Objects.equals(commentEntity.getCommentType(),CommentType.COMMENT.getType())){
            update.inc("commentCount",1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        Movement modify = mongoTemplate.findAndModify(query, update, options, Movement.class);
        //5、根据类型获取最新的评论数量，并返回
        if (modify==null){
            return 0;
        }
        return modify.getCommentTypeCount(commentEntity.getCommentType());
    }

    /**
     * 获取所有喜欢或者喜爱评论
     *
     * @param userId 用户id
     * @return {@link List}<{@link Comment}>
     */
    @Override
    public List<Comment> getAllLikeOrLoveComments(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId))
                .addCriteria(Criteria.where("commentType").ne(2));
        return  mongoTemplate.find(query,Comment.class);
    }

    @Override
    public Integer commentWhetherLike(String id, int isLike) {
        //构造查找当前评论条件
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(new ObjectId(id)));
        Update update = new Update();
        update.inc("likeCount",isLike);
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true) ;//获取更新后的最新数据
        Comment comment = mongoTemplate.findAndModify(query, update, options, Comment.class);
        if (comment==null){
            return 0;
        }
        return comment.getLikeCount();
    }

    /**
     * 得到当前用户的所有评论
     *
     * @param userId      用户id
     * @param page        页面
     * @param pageSize    页面大小
     * @param commentType 注释类型
     * @return {@link PageResult}<{@link Comment}>
     */
    @Override
    public PageResult<Comment> getAllCommentsByUserId(Long userId, Integer page, Integer pageSize, CommentType commentType) {
        Query query = new Query(Criteria.where("publishUserId").is(userId))
                .addCriteria(Criteria.where("userId").ne(userId))
                .addCriteria(Criteria.where("commentType").is(commentType.getType()));
        long count = mongoTemplate.count(query, Comment.class);
        query.skip((long) (page - 1) *pageSize)
                .limit(pageSize)
                .with(Sort.by(Sort.Order.desc("likeCount")))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return new PageResult<>(page,pageSize, (int) count,comments);
    }
}
